package com.wzdigit.wms.raw.service.backtosap;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.wzdigit.framework.Shift;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.IfPostback;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.AsnTypeEnum;
import com.wzdigit.wms.basic.enums.writeback.BackResultEnum;
import com.wzdigit.wms.basic.enums.writeback.OtherSystemEnum;
import com.wzdigit.wms.basic.enums.writeback.TopicEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.mapping.CodeMappingMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlGoodsMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.raw.service.mid.IfPostbackService;
import com.wzdigit.wms.web.service.common.wms2sap.ZDT_Reserve;
import com.wzdigit.wms.web.service.wms2sap.deliverywriteoff.ZDT_088_ReqRECORDSHEAD;
import com.wzdigit.wms.web.service.wms2sap.outstore.ZDT_071_ReqCDK;
import jodd.util.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/*
    * 交货单冲销
    * @author shuaic
    * @date 2021/6/18 18:44
*/
@Service
@Slf4j
public class DeliveryWriteOffService {
    @Autowired
    IfPostbackService ifPostbackService ;



    @Autowired
    SkuMapper skuMapper ;

    @Autowired
    CodeMappingMapper codeMappingMapper ;

    @Autowired
    WarehouseMapper warehouseMapper ;

    @Autowired
    AsnDtlGoodsMapper asnDtlGoodsMapper;

    @Autowired
    CodeMappingService codeMappingService;

    public  void deliveryWriteOffWriteBack(AsnHeader header, List<AsnDtl> dtlList ) throws  Exception{
        //存放公司间冲销数据
        List<ZDT_088_ReqRECORDSHEAD>  writeOffList = new ArrayList<>();



        String  orderNo="";
        String  orderLineNo = "";
        for(AsnDtl dtl  : dtlList){
            //外部单据直接取单号和行号
            if(AsnTypeEnum.R19.code.equals(header.getAsnType())&&header.getAsnNo().indexOf("R19") ==0 ){//自建单传源单号
                orderNo = header.getSourceNo();
                orderLineNo = dtl.getSourceLineNo();
            }else{//内部单据取来源单号和行号
                orderNo =header.getAsnNo();
                orderLineNo = dtl.getAsnLineNo()+"";
            }

            Sku sku = skuMapper.selectById(dtl.getSkuId());
            if(sku==null){
                String message = String.format("未找到ID为【%s】的SKU信息",dtl.getSkuId());
                Shift.fatal(StatusCode.BUSINESS_ERR, message);
            }

            //统计数量
            BigDecimal totalQty = asnDtlGoodsMapper.selectSumQtyByDtlId(dtl.getAsnDtlId());

            //查询仓库
            Warehouse warehouse = warehouseMapper.selectById(dtl.getWhsId());
            CodeMapping codeMapping = codeMappingService.selectByWhsCodeAndFactoryOrQaStatus(header.getFactory(), warehouse.getWhsCode(), dtl.getQaStatus());


                if(totalQty.compareTo(dtl.getOrderQty())!=0){
                    ZDT_088_ReqRECORDSHEAD writeOff =new ZDT_088_ReqRECORDSHEAD();
                    writeOff.setZDATE(DateUtil.format(new Date(),"yyyyMMdd"));
                    writeOff.setVBELN(orderNo);//单号
                    writeOff.setPOSNR(orderLineNo);//行号
                    writeOff.setWERKS(header.getFactory());//工厂
                    writeOff.setMATNR(sku.getSkuCode());//物料
                    writeOff.setLGORT(codeMapping.getMappingCode());//库存地点
                    writeOff.setLFIMG(totalQty+"");//交货单数量
                    writeOff.setLFIMG1(dtl.getOrderQty()+"");//实收数量
                    writeOff.setLFIMG2(dtl.getOrderQty().subtract(totalQty)+"");//差异数
                    writeOffList.add(writeOff);
                }
        }
        //生成回写数据
        if(writeOffList==null||writeOffList.size()==0){
            return ;
        }
        String jsonString = JSON.toJSONString(writeOffList);

        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackNo(orderNo);
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_DELIVERY_WRITE_OFF.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }




    }










    public  void deliveryWriteOffWriteBack(List<ZDT_088_ReqRECORDSHEAD>  list){
        //生成回写数据
        if(list==null||list.size()==0){
             return ;
        }
        String jsonString = JSON.toJSONString(list);

        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_DELIVERY_WRITE_OFF.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }

    }

}
